<template>
  <div class="upload">
    <div class="upload-wrapper">
      <div class="left">
        <loading v-if="!resourceData"></loading>
        <nodata v-else-if="!resourceData._id" />
        <user-info v-else :userInfo="resourceData"></user-info>
        <div class="user-resource">
          <ul class="slide-item">
            <h3 class="title">TA上传的资源列表</h3>
            <li
              v-for="(res,index) in resourceData.resource"
              :key="res._id"
              @click="gotoThisPage(res._id)"
              :class="resourceListIndex === index ? 'active': ''"
            >
              <div class="data">
                <div class="label">{{res.classChild}}</div>
                <div class="name">{{res.name}}</div>
              </div>
              <div class="number">
                <p>
                  下载所需积分：
                  <i>{{res.integral}}</i>
                </p>
                <p>
                  下载次数：
                  <i>{{res.downloadNumber}}</i>
                </p>
              </div>
              <div class="time" v-if="res.updated">
                <p>更新日期：{{res.updated | setDate}}</p>
              </div>
            </li>
          </ul>
        </div>
        <bei />
      </div>
      <div class="middle">
        <loading v-if="!thisResourceData" />
        <nodata v-else-if="!thisResourceData._id"></nodata>
        <div v-else class="middle-wrapper">
          <div class="resource-wrapping">
            <div class="intro">
              <div
                class="img"
                @click="zoomImg(thisResourceData.imageUrl)"
                :style="setImageUpload(thisResourceData.imageUrl)"
              ></div>
              <div class="content">
                <div class="name">
                  <div class="label">
                    <p class="resource-name">{{thisResourceData.name}}</p>
                    <p
                      v-if="thisResourceData.classChild"
                      class="class-data"
                    >--{{thisResourceData.classChild}}</p>
                  </div>
                  <div class="watch-number">
                    查看次数：
                    <i>{{thisResourceData.showNumber + showInitNumber}}</i>
                  </div>
                </div>
                <div class="number">
                  <p>
                    下载次数：
                    <i>{{thisResourceData.downloadNumber + downLoadInit}}</i>
                  </p>
                  <p>
                    下载所需积分：
                    <i>{{thisResourceData.integral}}</i>
                  </p>
                </div>
                <div class="time" v-if="thisResourceData.created">
                  <p>创建日期：{{thisResourceData.created | setDate}}</p>
                  <p>更新日期：{{thisResourceData.updated | setDate}}</p>
                </div>
              </div>
            </div>
            <div class="desc">
              <div class="desc-intro">
                <p class="resource-title">资源介绍：</p>
                <p class="resource-desc">{{thisResourceData.desc}}</p>
              </div>
              <div class="anlin">
                <p>如果觉得资源介绍太过简单，请私信作者，告知你在使用资源中遇到的问题。</p>
                <p>如果你有好的资源，也可以联系管理员或者站长，申请开通管理员的资格，然后便可以将您的资源上传到本站中。</p>
              </div>
            </div>
            <div class="resource-upload">
              <div class="upload-left">
                <p>下载方式：</p>
                <p>
                  注：本次下载需要消耗
                  <i>{{thisResourceData.integral}}</i> 积分
                </p>
                <p v-if="!thisResourceData.integral || integralInit">
                  你可以
                  <a
                    :href="thisResourceData.packageUrl | upload"
                    download="resource"
                    @click="addUploadNumber"
                  >点击这里</a> 进行下载。
                </p>
                <p v-else>
                  你可以使用积分下载，是否确认使用积分？
                  <el-button size="mini" @click="useIntegral(thisResourceData.integral)">确定</el-button>
                </p>
              </div>
              <div class="upload-right">
                <p @click="addStar()" class="star">点赞数：{{starNumber + starInit}}</p>
                <p>评论数：{{commentNumber}}</p>
              </div>
            </div>
          </div>
          <newComment
            class="new-comment"
            :thisData="thisResourceData"
            @_sendCommentNumber="_sendCommentNumber"
            ref="newcomment"
          ></newComment>
          <recomment :userName="thisResourceData.userName"></recomment>
        </div>
      </div>
      <div class="right">
        <ul>
          <li @click="addStar()">
            <button>赞</button>
          </li>
          <li @click="gotoPreResource()">
            <button :disabled="preDisabled" :style="{color: preDisabled ? '#999' : '#666'}">上一篇</button>
          </li>
          <li @click="gotoNextResource()">
            <button :disabled="nextDisabled" :style="{color: nextDisabled ? '#999' : '#666'}">下一篇</button>
          </li>
          <li @click="toComment()">
            <button>评论</button>
          </li>
          <li @click="addBrower()">
            <button>加入收藏</button>
          </li>
        </ul>
      </div>
    </div>
    <div class="pop-ups" v-if="popImage">
      <div class="img">
        <img :src="popImage | squareUrlsResource" alt />
      </div>
      <el-button @click="closePop()">
        <i class="el-icon-close"></i>
        关闭
      </el-button>
    </div>
  </div>
</template>

<script>
import { indexUrl } from "@/public/uri.js";
import recomment from "@/components/newComment/recomment";
import newComment from "@/components/newComment/index.vue";
import { setImageUpload } from "@/public/setBgImage.js";
import userInfo from "@/components/comment/newUserInfo.vue";
import { mapActions, mapState } from "Vuex";
import { slider } from "@/public/slider.js";
export default {
  name: "upload",
  components: {
    "user-info": userInfo,
    newComment,
    recomment
  },
  data() {
    return {
      id: "",
      resourceData: "",
      thisResourceData: "",
      setImageUpload: "",
      popImage: "",
      showInitNumber: 1,
      integralInit: 0,
      downLoadInit: 0,
      starNumber: 0,
      starInit: 0,
      commentNumber: 0,
      // 功能区数据
      preDisabled: true,
      nextDisabled: true,
      resourceListIndex: -1
    };
  },
  mounted() {
    this.setImageUpload = setImageUpload;
  },
  activated() {
    this.id = this.$route.params.id;
  },
  watch: {
    resourceListIndex() {
      // 监听index的值得变化，动态改变上一篇和下一篇的按钮的状态
      let data = this.resourceData.resource;
      if (data) {
        let maxLength = data.length;
        if (this.resourceListIndex === 0) {
          this.preDisabled = true;
          this.nextDisabled = false;
        } else if (this.resourceListIndex === maxLength - 1) {
          this.preDisabled = false;
          this.nextDisabled = true;
        } else {
          this.preDisabled = false;
          this.nextDisabled = false;
        }
        if (maxLength === 1) {
          this.preDisabled = true;
          this.nextDisabled = true;
        }
      }
    },
    $route(pre, now) {
      if (pre.name === "upload_id" && now.name === "upload_id") {
        this.id = this.$route.params.id;
      }
    },
    id() {
      if (this.id) {
        this.resourceData = "";
        this.thisResourceData = "";
        this.initmethods();
      }
    }
  },
  computed: {
    ...mapState("user", ["userInfoData"])
  },
  methods: {
    /*功能区方法******
     ***开始
     *******/
    gotoPreResource() {
      // 跳转到上一篇的资源
      let resourceListIndex = this.resourceListIndex,
        resource = this.resourceData.resource;
      resourceListIndex -= 1;
      this.$router.push("/upload/" + resource[resourceListIndex]._id);
    },
    gotoNextResource() {
      // 跳转到下一篇的资源
      let resourceListIndex = this.resourceListIndex,
        resource = this.resourceData.resource;
      resourceListIndex += 1;
      this.$router.push("/upload/" + resource[resourceListIndex]._id);
    },
    toComment() {
      // 评论区域获取焦点
      location.href = "#/comment-box";
      this.$refs.newcomment.$refs.message.$refs.commentBox.focus();
    },
    addBrower() {
      // 加入收藏
      let sURL = indexUrl + this.$route.path;
      const sTitle = "共享资源";
      sURL = encodeURI(sURL);
      try {
        window.external.addFavorite(sURL, sTitle);
      } catch (e) {
        try {
          window.sidebar.addPanel(sTitle, sURL, "");
        } catch (e) {
          alert(
            "您的浏览器不支持自动加入收藏功能，请使用Ctrl+D进行添加，或手动在浏览器里进行设置！"
          );
        }
      }
    },
    /*功能区方法******
     ***结束
     *******/
    _sendCommentNumber(number) {
      this.commentNumber = number;
    },
    addStar() {
      // 添加点赞数
      let ip = returnCitySN.cip;
      this.setStar({
        ip,
        id: this.id,
        parentFlog: true
      })
        .then(res => {
          if (res.data.ok === 1) {
            this.starInit = 1;
            alert(res.data.data);
          } else {
            alert(res.data.data);
          }
        })
        .catch(err => {
          cosole.log("err");
        });
    },
    addUploadNumber() {
      this.addThisUploadNumber({ id: this.id })
        .then(res => {
          if (res.data.ok === 1) {
            this.downLoadInit += 1;
            console.log("ok");
          } else {
            console.log("err");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    useIntegral(num) {
      // 使用积分
      if (this.userInfoData) {
        if (this.userInfoData.integral >= num) {
          this.delIntegral({
            num,
            userName: this.userInfoData.userName,
            getUserName: this.thisResourceData.userName
          })
            .then(res => {
              if (res.data.ok === 1) {
                this.integralInit = 1;
                alert("你的积分已经被扣除，你现在可以进行点击下载此资源。");
              } else {
                alert("积分扣除出错，如有问题请联系管理员。");
              }
            })
            .catch(err => {
              alert("程序出错，请刷新重试，如有问题，请联系管理员！");
            });
        } else {
          alert("你的积分不足够扣除，请先累计积分再进行下载！");
        }
      } else {
        alert("你还未登录，请先登录！");
      }
    },
    closePop() {
      this.popImage = "";
    },
    zoomImg(imgUrl) {
      this.popImage = imgUrl;
    },
    gotoThisPage(id) {
      this.$router.push("/upload/" + id);
    },
    initmethods() {
      let id = this.id;
      this.getUploadData({ id })
        .then(res => {
          if (res.data.ok === 1) {
            this.resourceData = res.data.data;
            this.$nextTick(() => {
              slider(document.getElementsByClassName("slide-item")[0]);
            });

            let resource = res.data.data.resource;
            for (let i = 0; i < resource.length; i++) {
              if (resource[i]._id === this.id) {
                this.thisResourceData = resource[i];
                this.resourceListIndex = i;
                break;
              }
            }
          } else {
            this.resourceData = {};
          }
        })
        .catch(err => {
          console.log(err);
        });

      this.addThisWatchNumber({ id });
      this.getSkillStar({ id: this.id })
        .then(res => {
          if (res.data.ok === 1) {
            this.starNumber = res.data.data.length;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    ...mapActions("user", [
      "getUploadData",
      "addThisWatchNumber",
      "delIntegral",
      "addThisUploadNumber",
      "setStar",
      "getSkillStar"
    ])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
.upload
  width: 100%
  padding: 20px 0
  .upload-wrapper
    width: 1280px
    margin: 0 auto
    @include flex(space-between,flex-start)
    .left
      flex: 0 0 25%
      width: 25%
      .user-resource
        margin-top: 10px
        width: 100%
        background-color: #fff
        >ul
          width: 100%    
          padding: 10px
          overflow: hidden      
          .title
            width: 100%
            color: #333
            height: 40px
            line-height: 40px
            padding-left: 10px
            @include text-overflow()
            @include title-before(5px,16px,12px,0px,#eb2001)
          .active
            background-color: #f3f3f3
          >li
            width: 100%
            padding: 0 10px
            border-bottom: 1px solid #eee 
            cursor: pointer
            .data
              line-height: 30px
              height: 30px
              @include text-overflow()
              @include flex(space-between,center)
              .label
                color: #999
              .name
                color: #333
            .number
              height: 30px
              line-height: 30px
              @include text-overflow()
              @include flex(space-between,center)
              i
                color: #eb2001
            .time
              height: 30px
              line-height: 30px
            &:last-child
              border: none
            &:hover
              .data
                .name
                  color: #0487dc
                  font-weight: 700
    .middle
      width: 67%
      flex: 0 0 67%
      .resource-wrapping
        width: 100%
        background: #fff
        padding: 20px
        .intro
          width: 100%
          padding-bottom: 20px
          border-bottom: 2px solid #eee
          @include flex(space-between,flex-start)
          .img
            flex: 0 0 100px
            width: 100px
            height: 100px
            box-shadow: 2px 2px 2px rgba(0,0,0,.08)
            cursor: pointer
            @include setbackground()
          .content
            flex: 1
            heigth: 100px
            padding: 0 0 0 20px
            .name
              width: 100%
              height: 40px
              line-height: 40px
              @include flex(space-between,center)
              .label
                width: 100%
                >p
                  margin-right: 20px
                  display: inline-block
                .resource-name
                  font-size: 21px
                  font-weight: 700
                  color: #333
                .class-data
                  color: #999
              .watch-number
                flex: 0 0 100px
                text-align: right       
                i
                  color: #eb2001         
            .time
              width: 100%
              line-height: 30px
              height: 30px
              @include flex(space-between,center)
            .number
              width: 100%
              height: 30px
              line-height: 30px
              i
                color: #eb2001  
              @include flex(space-between,center)
        .desc
          width: 100%
          .desc-intro
            width: 100%
            padding: 20px 0
            border-bottom: 1px solid #f9f9f9
            .resource-title
              width: 100%
              line-height: 30px
              height: 30px
              font-size: 18px
              color: #333
            .resource-desc
              width: 100%
              padding: 10px 0
              line-height: 20px
              text-indent: 2em
              white-space: pre-wrap
          .anlin
            padding: 20px 0
            line-height: 30px
            border-bottom: 2px solid #eee
            overflow: hidden
        .resource-upload
          width: 100%
          padding: 20px 0
          @include flex(space-between,flex-start)
          .upload-left
            width: 80%
            flex: 0 0 80%
            >p
              width: 100%
              height: 30px
              line-height: 30px
              &:nth-child(1)
                font-size: 18px
                color: #333
              &:nth-child(2)
                i
                  color: #eb2001
              &:nth-child(3)
                a
                  text-decoration: underline
                  color: #0487dc
          .upload-right
            flex: 1
            width: 20%
            text-align: center
            line-height: 30px
            .star
              cursor: pointer
      .new-comment
        width: 100%
        margin-top: 10px
    .right
      flex: 0 0 6%   
      width: 6%
      background-color: #fff   
      overflow: hidden
      >ul
        width: 100%
        text-align: center
        >li
          width: 100%
          height: 30px
          line-height: 30px
          border-bottom: 1px solid #eee
          cursor: pointer  
          >button
            width: 100%
            height: 100%
          &:hover
            background-color: #fafafa
  .pop-ups
    width: 100%
    min-height: 100vh
    position: fixed
    left: 0
    top: 0
    background-color: #000
    .el-button
      position: absolute
      right: 40px
      top: 40px
    .img
      width: 100%
      height: 100vh
      @include flex(center,center)
      img
        max-width: 100%
        max-height: 100%
</style>